//
//  UICutter.m
//  cutter
//
//  Created by mac on 15/12/8.
//  Copyright © 2015年 e360. All rights reserved.
//
#import "TMGrid.h"
#import "TMCutter.h"
#import "TMCutterLayer.h"
#import "TMCutterContent.h"
#import "TMCutterSelector.h"

@interface TMCutter () 
@property(nonatomic,strong) NSMutableArray *undoStack;
@property(nonatomic,strong) NSMutableArray *redoStack;
@end
@implementation TMCutter{
    TMCutterSelector *selectorView;
    TMCutterContent *contentView;
    TMGrid *gridView;
}
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self initInstance];
    }
    return self;
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self initInstance];
    }
    return self;
}
-(void)initInstance{
    [self setAutoresizesSubviews:YES];
    [self.layer setMasksToBounds:YES];
    //
    gridView = [[TMGrid alloc] initWithFrame:self.bounds];
    [gridView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
    [self addSubview:gridView];
    [gridView setHidden:YES];
    //
    contentView = [[TMCutterContent alloc] initWithFrame:CGRectZero];
    [self addSubview:contentView];
    //
    selectorView = [[TMCutterSelector alloc] initWithFrame:self.bounds];
    [selectorView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
    [self addSubview:selectorView];
    //
    [self reset];
}
-(void)setBounds:(CGRect)bounds{
    [super setBounds:bounds];
    [contentView setCenter:CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds))];
    [self updateTransform];
}
-(void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    [gridView setNeedsDisplay];
    [selectorView setNeedsDisplay];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    if([touches count] == 1) {
        [selectorView touchesBegan:touches withEvent:event];
    }
    [super touchesBegan:touches withEvent:event];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    if([touches count] == 1) {
        [selectorView touchesMoved:touches withEvent:event];
        if (selectorView.target == nil) {
            UITouch *touch = [touches anyObject];
            CGPoint curPoint = [touch locationInView:self];
            CGPoint prePoint = [touch previousLocationInView:self];
            //
            self.offsetX += curPoint.x - prePoint.x;
            self.offsetY += curPoint.y - prePoint.y;
            [self updateTransform];
        }else{
            [self setNeedsDisplay];
        }
    }
    if([touches count] == 2) {
        UITouch *touchA = [[touches allObjects] objectAtIndex:0];
        UITouch *touchB = [[touches allObjects] objectAtIndex:1];
        CGPoint prePointA = [touchA previousLocationInView:self];
        CGPoint prePointB = [touchB previousLocationInView:self];
        CGPoint curPointA = [touchA locationInView:self];
        CGPoint curPointB = [touchB locationInView:self];
        //
        self.scale *= [self getDistance:curPointA b:curPointB] / [self getDistance:prePointA b:prePointB];
        self.offsetX += ((curPointA.x + curPointB.x) - (prePointA.x + prePointB.x)) * 0.5;
        self.offsetY += ((curPointA.y + curPointB.y) - (prePointA.y + prePointB.y)) * 0.5;
        [self updateTransform];
    }
    [super touchesMoved:touches withEvent:event];
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if([touches count] == 1) {
        [selectorView touchesEnded:touches withEvent:event];
    }
    [self execute];
    [super touchesEnded:touches withEvent:event];
}
-(CGFloat)getDistance:(CGPoint)a b:(CGPoint)b{
    CGFloat dx = a.x - b.x;
    CGFloat dy = a.y - b.y;
    return sqrt(dx * dx + dy * dy);
}
//
//文档属性**************************************
-(void)updateTransform{
    CGAffineTransform transform = CGAffineTransformIdentity;
    transform = CGAffineTransformTranslate(transform, self.offsetX, self.offsetY);
    transform = CGAffineTransformScale(transform, self.scale, self.scale);
    [contentView setTransform:transform];
    [self setNeedsDisplay];
}
-(void)setShowGrid:(BOOL)showGrid{
    [gridView setHidden:!showGrid];
}
-(BOOL)showGrid{
    return !gridView.hidden;
}
-(void)setOffsetX:(CGFloat)offsetX{
    [gridView setOffsetX:offsetX];
}
-(void)setOffsetY:(CGFloat)offsetY{
    [gridView setOffsetY:offsetY];
}
-(void)setScale:(CGFloat)scale{
    [gridView setScale:scale];
}
-(CGFloat)offsetX{
    return [gridView offsetX];
}
-(CGFloat)offsetY{
    return [gridView offsetY];
}
-(CGFloat)scale{
    return [gridView scale];
}
//导入
-(void)import:(NSDictionary*)data{
    [selectorView setTarget:nil];
    [contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [contentView setCenter:CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds))];
    [self setOffsetX:0];
    [self setOffsetY:0];
    [self setScale:1];
    //
    if (data != nil) {
        NSArray *layers = [data valueForKey:TMCutterAttributeLayers];
        for (NSDictionary *temp in layers) {
            NSInteger type = [[temp valueForKey:TMCutterAttributeType] integerValue];
            if (type == MatchLayerTypeLabel) {
                TMCutterLabel *layer = [TMCutterLabel layer:temp];
                [contentView addSubview:layer];
                [layer setDelegate:self];
            }
            if (type == MatchLayerTypeImage) {
                TMCutterImage *layer = [TMCutterImage layer:temp];
                [contentView addSubview:layer];
                [layer setDelegate:self];
            }
        }
        [self setScale:[[data valueForKey:TMCutterAttributeScale] floatValue]];
        [self setOffsetX:[[data valueForKey:TMCutterAttributeOffsetX] floatValue]];
        [self setOffsetY:[[data valueForKey:TMCutterAttributeOffsetY] floatValue]];
    }
    [self updateTransform];
}
//导出
-(NSDictionary*)export{
    if (contentView.subviews.count > 0) {
        NSMutableArray *layers = [NSMutableArray array];
        NSMutableArray *identifier = [NSMutableArray array];
        for (TMCutterLayer *layer in contentView.subviews) {
            [layers addObject:layer.data];
            //
            id iid = [layer valueForKey:TMCutterAttributeIdentifier];
            if (iid) {
                [identifier addObject:iid];
            }
        }
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        [data setValue:[NSArray arrayWithArray:layers] forKey:TMCutterAttributeLayers];
        [data setValue:[NSNumber numberWithFloat:self.scale] forKey:TMCutterAttributeScale];
        [data setValue:[NSNumber numberWithFloat:self.offsetX] forKey:TMCutterAttributeOffsetX];
        [data setValue:[NSNumber numberWithFloat:self.offsetY] forKey:TMCutterAttributeOffsetY];
        [data setValue:[NSArray arrayWithArray:identifier] forKey:TMCutterAttributeIdentifier];
        return [NSDictionary dictionaryWithDictionary:data];
    }
    return nil;
}
//重置
-(void)reset{
    [self setUndoStack:[NSMutableArray array]];
    [self setRedoStack:[NSMutableArray array]];
    [self setChange:NO];
    [self import:nil];
}
//
//图层属性**************************************
-(void)cutterLayerResize:(TMCutterLayer*)layer{
    if (layer == selectorView.target) {
        [selectorView setNeedsDisplay];
    }
}
-(NSInteger)numChildren{
    return [contentView.subviews count];
}
-(void)setFocusObject:(TMCutterLayer *)focusObject{
    [selectorView setTarget:focusObject];
    [selectorView setNeedsDisplay];
    [focusObject setNeedsLayout];
    [self execute];
}
-(TMCutterLayer *)focusObject{
    return selectorView.target;
}
-(void)setChildIndex:(TMCutterLayer*)child index:(NSInteger)index{
    if (index < 0) {
        index = 0;
    }
    if (index < [contentView.subviews count]) {
        [contentView insertSubview:child atIndex:index];
        [self execute];
    }
}
-(NSInteger)getChildIndex:(TMCutterLayer*)child{
    return [contentView.subviews indexOfObject:child];
}
-(void)removeChild:(TMCutterLayer*)child{
    if ([contentView.subviews indexOfObject:child] != NSNotFound) {
        [child removeFromSuperview];
        [self execute];
        //
        if (selectorView.target == child) {
            [selectorView setTarget:nil];
            [selectorView setNeedsDisplay];
        }
    }
}
-(void)addChild:(TMCutterLayer*)child{
    [contentView addSubview:child];
    [child setDelegate:self];
    [self execute];
}
//
//历史记录**************************************
-(NSInteger)numUndo{
    return [self.undoStack count];
}
-(NSInteger)numRedo{
    return [self.redoStack count];
}
//入栈
-(void)execute{
    NSDictionary *data = [self export];
    if (data != nil) {
        if ([data isEqual:[self.undoStack lastObject]] == NO) {
            [self.undoStack addObject:data];
            [self setChange:YES];
        }
    }
}
//撤销
-(void)undo{
    NSDictionary *data = [self.undoStack lastObject];
    if (data != nil) {
        [self.undoStack removeObject:data];
        [self.redoStack addObject:data];
        //
        data = [self.undoStack lastObject];
        if (data != nil) {
            [self setChange:YES];
            [self import:data];
        }
    }
}
//重做
-(void)redo{
    NSDictionary *data = [self.redoStack lastObject];
    if (data != nil) {
        [self.redoStack removeObject:data];
        [self.undoStack addObject:data];
        [self setChange:YES];
        [self import:data];
    }
}
@end